package com.cheyunkeji.er.utils;

import android.app.Activity;
import android.app.Service;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.Resources;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.PowerManager;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;


import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.MyApplication;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

/**
 * 共通功能
 *
 * @author wangyajun
 */

public class SUtil {
//    private static final LogUtil log = new LogUtil("SUtils");
    /**
     * 上下文
     */
    public static Context appContext = MyApplication.getInstance();
    /**
     * 密度
     */
    public static float density = 1.0f;

    /**
     * 获取app上下文
     */
    public static Context getAppContext() {
        return appContext;
    }

    /**
     * 隐藏键盘
     *
     * @param isClearFoces 如果随意清空焦点会引发焦点被父控件获取，会导致上上层scroll类滑动
     * @param act
     */
    public static void dismissKeyboard(Activity act, boolean isClearFoces) {
        if (null == act)
            return;
        try {
            InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
            View focus = act.getCurrentFocus();
            if (null != focus) {
                imm.hideSoftInputFromWindow(focus.getWindowToken(), 0);
                if (isClearFoces) {
                    focus.clearFocus();
                }
            }
        } catch (Exception e) {
//            log.e("dismissKeyboard", e.toString());
        }
    }

    public static void dismissKeyboard(Activity act) {
        dismissKeyboard(act, true);
    }

    /**
     * 隐藏键盘
     *
     * @param view
     */
    public static void dismissKeyboard(View view) {
        if (null == view)
            return;
        try {
            InputMethodManager imm = (InputMethodManager) appContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            view.clearFocus();
        } catch (Exception e) {
//            log.e("dismissKeyboard", e.toString());
        }
    }

    public static boolean isKeyBoardShowing(EditText mEditText) {
        InputMethodManager inputMethodManager = (InputMethodManager) appContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager.isActive(mEditText)) {
            return true;
        }
        return false;
    }

    /**
     * 弹出键盘
     *
     * @param view
     */
    public static void showKeyboard(View view) {
        if (null == view)
            return;
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        InputMethodManager m = (InputMethodManager) appContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        m.showSoftInput(view, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 弹出键盘
     *
     * @param view
     */
    public static void showKeyboard(final EditText view) {
        if (null == view)
            return;
        view.requestFocus();
        view.postDelayed(new Runnable() {

            @Override
            public void run() {
                InputMethodManager inputMethodManager = (InputMethodManager) appContext
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.showSoftInput(view, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 500);
    }

    /**
     * 弹出键盘 -- 没有延迟
     *
     * @param view
     */
    public static void showKeyboardWithNoDelay(final EditText view) {
        if (null == view)
            return;
        view.requestFocus();
        view.setFocusableInTouchMode(true);
        InputMethodManager inputMethodManager = (InputMethodManager) appContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(view, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 键盘状态切换
     */
    public static void toggleSoftInput() {
        InputMethodManager m = (InputMethodManager) appContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 获取任务栏高度
     *
     * @param context activity的context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        Window window = ((Activity) context).getWindow();
        Rect frame = new Rect();
        window.getDecorView().getWindowVisibleDisplayFrame(frame);
        return frame.top;
    }

    /**
     * 取得屏幕高度（含任务栏、不含导航栏的高度）
     *
     * @return 像素
     */
    public static int getAvailableH() {
        DisplayMetrics metrics = appContext.getResources().getDisplayMetrics();
        return metrics.heightPixels;
    }

    /**
     * 设置View的高度，原参数不变
     *
     * @param view
     * @param height
     */
    public static void setViewHeight(View view, int height) {
        if (null == view)
            return;
        ViewGroup.LayoutParams lp = view.getLayoutParams();
        if (null == lp) {
            lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        lp.height = height;
        view.setLayoutParams(lp);
    }

    /**
     * 取得屏幕宽度
     *
     * @return 像素
     */
    public static int getAvailableW() {
        DisplayMetrics metrics = appContext.getResources().getDisplayMetrics();
        return metrics.widthPixels;
    }

    /**
     * 震动一下下
     */
    public static void vibrate() {
        Vibrator mVibrator = (Vibrator) appContext.getSystemService(Service.VIBRATOR_SERVICE);
        mVibrator.vibrate(new long[]{10, 100}, -1);
        mVibrator.cancel();
    }

    /**
     * 震动两下
     */
    public static void vibrate2() {
        final Vibrator mVibrator = (Vibrator) appContext.getSystemService(Service.VIBRATOR_SERVICE);
        mVibrator.vibrate(new long[]{500, 250, 150, 100}, -1);
    }

    /**
     * 读取表情配置文件
     *
     * @param context
     * @return
     */
    public static List<String> getFaceFile(Context context) {
        try {
            List<String> list = new ArrayList<String>();
            InputStream in = context.getResources().getAssets().open("face");
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String str = null;
            while ((str = br.readLine()) != null) {
                list.add(str);
            }

            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 读取Assets目录文件
     *
     * @param fileName 文件名
     * @return
     */
    public static String getAssetsFile(String fileName) {
        try {
            String str = null;
            InputStream in = appContext.getResources().getAssets().open(fileName);
            int length = in.available();
            byte[] buffer = new byte[length];
            in.read(buffer);
            in.close();
            str = new String(buffer);
            return str;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 检查网络状态
     *
     * @return 0：断网，1：移动网络，2：wifi
     */
    public static int checkNetworkInfo() {
        // wifi
        NetworkInfo.State wifi = null;
        // mobile
        NetworkInfo.State mobile = null;
        try {
            ConnectivityManager conMan = (ConnectivityManager) appContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo wifiInfo = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            NetworkInfo mobileInfo = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            // wifi
            wifi = null != wifiInfo ? wifiInfo.getState() : null;
            // mobile
            mobile = null != mobileInfo ? mobileInfo.getState() : null;
        } catch (Exception e) {
//            log.e("checkNetworkInfo", e.toString());
        }
        if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
            return 1;
        if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
            return 2;

        return 0;
    }

    /**
     * 获取网络类型
     *
     * @return
     */
    public static String getNetworkName(int currentNetState) {
        switch (currentNetState) {
            case 0:
                return "offline";
            case 1:
                return "gnet";
            case 2:
                return "wifi";
        }
        return "";
    }

    /**
     * 播放系统Notification提示音
     */
    public static void playDefaultSound() {
        Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        MediaPlayer player = new MediaPlayer();
        try {
            player.setDataSource(appContext, alert);
        } catch (IllegalArgumentException e1) {
            e1.printStackTrace();
        } catch (SecurityException e1) {
            e1.printStackTrace();
        } catch (IllegalStateException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        AudioManager audioManager = (AudioManager) appContext.getSystemService(Context.AUDIO_SERVICE);
        if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) != 0) {
            player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
            player.setLooping(false);
            try {
                player.prepare();
                player.start();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 获取签名信息
     */
    public static Signature getSingInfo() {
        try {
            PackageInfo packageInfo = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(),
                    PackageManager.GET_SIGNATURES);
            Signature[] signs = packageInfo.signatures;
            Signature sign = signs[0];
            return sign;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 转换签名信息
     */
    public static String parseSignature() {
        try {
            Signature sign = getSingInfo();
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(sign
                    .toByteArray()));
            String pubKey = cert.getPublicKey().toString();
//            log.d("parseSignature", pubKey);
            String signNumber = cert.getSerialNumber().toString();
//            log.d("signNumber", signNumber);
            return pubKey + ", " + signNumber;
        } catch (CertificateException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取屏幕状态
     *
     * @return true：点亮，false：关闭
     */
    public static boolean getScreenState() {
        PowerManager pm = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
        return pm.isScreenOn();
    }

    /**
     * 获取像素
     *
     * @param dipValue
     * @return
     */
    public static int getPixels(int dipValue) {
        Resources r = appContext.getResources();
        int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, r.getDisplayMetrics());
        return px;
    }

    /**
     * 跳转到应用市场
     *
     * @param context
     * @param pkg
     */
    public static void goMarket(Context context, String pkg) {
        if (null == context)
            return;
        try {
            Uri uri = Uri.parse("market://details?id=" + pkg);
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(it);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 开启activity
     *
     * @param ctx
     * @param i
     */
    public static void startActivity(Context ctx, Intent i) {
        if (null == ctx)
            return;
        ctx.startActivity(i);
        startActivityAnim((Activity) ctx);
    }

    /**
     * 开启activity
     *
     * @param act
     * @param i
     */
    public static void startActivity(Activity act, Intent i) {
        if (null == act)
            return;
        act.startActivity(i);
        startActivityAnim(act);
    }

    /**
     * 关闭activity
     *
     * @param act
     */
    public static void finish(Activity act) {
        if (null == act)
            return;
        if (!act.isFinishing())
            act.finish();
        finishActivityAnim(act);
    }

    /**
     * 打开activity动画
     *
     * @param act
     */
    public static void startActivityAnim(Activity act) {
        if (null != act) {
            act.overridePendingTransition(R.anim.act_in_screen_r_to_l, android.R.anim.fade_out);
        }
    }

    /**
     * 打开activity动画
     *
     * @param act
     */
    public static void startActivityAnim(Activity act, int enterAnim, int exitAnim) {
        if (null != act) {
            act.overridePendingTransition(enterAnim, exitAnim);
        }
    }

    /**
     * 关闭activity动画
     *
     * @param act
     */
    public static void finishActivityAnim(Activity act) {
        if (null != act) {
            act.overridePendingTransition(R.anim.na, R.anim.act_out_screen_l_to_r);
        }

    }

    /**
     * 获取版本
     *
     * @return
     */
    public static String getVersionName() {
        try {
            PackageInfo pi = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0);
            return pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 复制到剪贴板
     *
     * @param content
     */
    public static String copy(String content) {
        ClipboardManager cmb = (ClipboardManager) appContext.getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content);

        return content;
    }

    /**
     * 获取字符串
     *
     * @param resId
     * @return
     */
    public static String getString(int resId) {
        return appContext.getString(resId);
    }

    /**
     * List是否为空
     *
     * @param list
     * @return
     */
    public static boolean isListEmpty(List<?> list) {
        return null == list || list.size() == 0;

    }

    // View宽，高
    public static int[] getLocation(View v) {
        int[] loc = new int[4];
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        loc[0] = location[0];
        loc[1] = location[1];
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        v.measure(w, h);

        loc[2] = v.getMeasuredWidth();
        loc[3] = v.getMeasuredHeight();

        return loc;
    }

    /**
     * 获取距离屏幕的高度
     */
    public static int getViewTopH(View v) {
        if (null == v) {
            return 0;
        }

        int[] wh = getLocation(v);
        return wh[1];
    }
}
